package cc.rengu.igas.channel.alipay.core.service.trans;

import cc.rengu.igas.channel.alipay.common.constant.AlipayConfigConstant;
import cc.rengu.igas.channel.alipay.common.constant.AlipayParamConstant;
import cc.rengu.igas.channel.alipay.common.constant.AlipayTreeNodeConstant;
import cc.rengu.igas.channel.alipay.common.enums.RespCodeEnum;
import cc.rengu.igas.channel.alipay.core.model.ChnlBizResponse;
import cc.rengu.igas.channel.alipay.core.service.base.PayService;
import cc.rengu.igas.channel.alipay.facade.request.ActivityConfirmRequest;
import cc.rengu.igas.channel.alipay.facade.response.ActivityConfirmResponse;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.dao.CertInfoMapper;
import cc.rengu.oltp.service.common.dao.SecPlanInfoMapper;
import cc.rengu.oltp.service.common.dao.impl.CertInfoMapperImpl;
import cc.rengu.oltp.service.common.dao.impl.SecPlanInfoMapperImpl;
import cc.rengu.oltp.service.common.entity.*;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.realize.SysParamService;
import cc.rengu.oltp.service.realize.impl.SysParamServiceImpl;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.StringUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AntMerchantExpandIndirectActivityConfirmModel;
import com.alipay.api.request.AntMerchantExpandIndirectActivityConfirmRequest;
import com.alipay.api.response.AntMerchantExpandIndirectActivityConfirmResponse;

import java.util.List;
import java.util.Optional;

/**
 * 支付宝营销活动报名
 * 间连商户运营活动确认
 */
public class ActivityConfirmService extends PayService {
    @Override
    protected Object beforeBizProcess() throws Exception {
        ActivityConfirmRequest activityConfirmRequest = new ActivityConfirmRequest();
        ConvertUtil.convertOutput(activityConfirmRequest);
        return activityConfirmRequest;
    }

    @Override
    protected ChnlBizResponse callBizService(Object request) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        ActivityConfirmResponse activityConfirmResponse = new ActivityConfirmResponse();
        ActivityConfirmRequest activityConfirmRequest = (ActivityConfirmRequest) request;
        DstChannelCfg dstChannelCfg = (DstChannelCfg) xmlTreeUtil.getXmlTreeObjectValue(AlipayTreeNodeConstant.DST_CHANNEL_CFG, DstChannelCfg.class);
        String instId = activityConfirmRequest.getHeader().getInstId();
        ChnlBizResponse chnlBizResponse = new ChnlBizResponse();
        /* 支付宝支付参数获取 */
        /*请求类型*/
        String aliPayUrl = null;
        /*报文类型*/
        String msgType = null;
        /*字符类型*/
        String charset = null;
        /*签名类型*/
        String signType = null;
        /*签名私钥*/
        String priKey = null;
        /*签名公钥*/
        String pubKey = null;
        /*代理IP*/
        String proxyIp = null;
        /*代理端口*/
        String proxyPort = null;
        SysParamService sysParamService = new SysParamServiceImpl();
        SysParam sysParam = sysParamService.getSysParamInfo(AppParamConstant.DEFAULT_INSTID,
                AlipayConfigConstant.ALIPAY_CONF_NODE, AlipayConfigConstant.ALIPAY_SWITCH_FLAG);
        if ("ZX".equals(sysParam.getParamValue())) {
            /*专线*/
            /*获取url*/
            sysParam = sysParamService.getSysParamInfo(AppParamConstant.DEFAULT_INSTID,
                    AlipayConfigConstant.ALIPAY_CONF_NODE, AlipayConfigConstant.ALIPAY_PAY_ZX_URL);
            if (null != sysParam && !StringUtil.isEmptyOrNull(sysParam.getParamValue())) {
                aliPayUrl = sysParam.getParamValue();
            } else {
                rglog.error("未配置支付宝直连专线URL地址，请配置");
                throw new BizException(RespCodeEnum.CONFIG_PARAM_NOT_EXIST.getRespCode(),
                        RespCodeEnum.CONFIG_PARAM_NOT_EXIST.getRespDesc());
            }
            /*专线代理IP*/
            sysParam = sysParamService.getSysParamInfo(AppParamConstant.DEFAULT_INSTID,
                    AlipayConfigConstant.ALIPAY_CONF_NODE, AlipayConfigConstant.ALIPAY_PROXY_ZX_IP);
            if (null != sysParam && !StringUtil.isEmptyOrNull(sysParam.getParamValue())) {
                proxyIp = sysParam.getParamValue();
            } else {
                rglog.error("未配置支付宝直连专线IP地址，请配置");
                throw new BizException(RespCodeEnum.CONFIG_PARAM_NOT_EXIST.getRespCode(),
                        RespCodeEnum.CONFIG_PARAM_NOT_EXIST.getRespDesc());
            }
            /*专线代理端口*/
            sysParam = sysParamService.getSysParamInfo(AppParamConstant.DEFAULT_INSTID,
                    AlipayConfigConstant.ALIPAY_CONF_NODE, AlipayConfigConstant.ALIPAY_PROXY_ZX_PORT);
            if (null != sysParam && !StringUtil.isEmptyOrNull(sysParam.getParamValue())) {
                proxyPort = sysParam.getParamValue();
            } else {
                rglog.error("未配置支付宝直连专线IP地址，请配置");
                throw new BizException(RespCodeEnum.CONFIG_PARAM_NOT_EXIST.getRespCode(),
                        RespCodeEnum.CONFIG_PARAM_NOT_EXIST.getRespDesc());
            }
        } else {
            /*互联网获取url*/
            sysParam = sysParamService.getSysParamInfo(instId, AlipayConfigConstant.ALIPAY_CONF_NODE, AlipayConfigConstant.ALIPAY_PAY_NET_URL);
            if (null == sysParam || StringUtil.isEmptyOrNull(sysParam.getParamValue())) {
                rglog.error("未配置支付宝直连专线URL地址，请配置");
                throw new BizException(RespCodeEnum.CONFIG_PARAM_NOT_EXIST.getRespCode(), RespCodeEnum.CONFIG_PARAM_NOT_EXIST.getRespDesc());
            }
            aliPayUrl = sysParam.getParamValue();
            /*互联网代理IP*/
            sysParam = sysParamService.getSysParamInfo(instId, AlipayConfigConstant.ALIPAY_CONF_NODE, AlipayConfigConstant.ALIPAY_PROXY_NET_IP);
            proxyIp = (null == sysParam || StringUtil.isEmptyOrNull(sysParam.getParamValue())) ? null : sysParam.getParamValue().trim();
            /*互联网代理端口*/
            sysParam = sysParamService.getSysParamInfo(instId, AlipayConfigConstant.ALIPAY_CONF_NODE, AlipayConfigConstant.ALIPAY_PROXY_NET_PORT);
            proxyPort = (null == sysParam || StringUtil.isEmptyOrNull(sysParam.getParamValue())) ? null : sysParam.getParamValue().trim();
        }
        sysParam = sysParamService.getSysParamInfo(AppParamConstant.DEFAULT_INSTID,
                AlipayConfigConstant.ALIPAY_CONF_NODE, AlipayConfigConstant.ALIPAY_MSG_TYPE);
        if (null != sysParam && !StringUtil.isEmptyOrNull(sysParam.getParamValue())) {
            msgType = sysParam.getParamValue();
        } else {
            rglog.warn("未配置支付宝直连报文类型，默认json");
            msgType = "json";
        }
        sysParam = sysParamService.getSysParamInfo(AppParamConstant.DEFAULT_INSTID,
                AlipayConfigConstant.ALIPAY_CONF_NODE, AlipayConfigConstant.ALIPAY_CHARSET);
        if (null != sysParam && !StringUtil.isEmptyOrNull(sysParam.getParamValue())) {
            charset = sysParam.getParamValue();
        } else {
            rglog.warn("未配置支付宝直连字符类型，默认UTF-8");
            charset = "UTF-8";
        }
        sysParam = sysParamService.getSysParamInfo(AppParamConstant.DEFAULT_INSTID,
                AlipayConfigConstant.ALIPAY_CONF_NODE, AlipayConfigConstant.ALIPAY_SIGN_TYPE);
        if (null != sysParam && !StringUtil.isEmptyOrNull(sysParam.getParamValue())) {
            signType = sysParam.getParamValue();
        } else {
            rglog.warn("未配置支付宝直连加签类型，默认RSA2");
            signType = "RSA2";
        }
        /* 根据通道安全计划获取安全计划 */
        SecPlanInfoMapper secPlanInfoMapper = new SecPlanInfoMapperImpl();
        CertInfoMapper certInfoMapper = new CertInfoMapperImpl();
        List<SecPlanInfo> secPlanInfoList = secPlanInfoMapper.selectSecPlanInfoBySecPlanId(instId, dstChannelCfg.getSecPlanId());
        /* 获取签名验签证书 */
        Optional<SecPlanInfo> secPlanInfoOptSign = secPlanInfoList.stream().filter(item -> item.getSecPlanType().equals(AlipayParamConstant.SIGN_CERT_TYPE)).findFirst();
        if (secPlanInfoOptSign.isPresent()) {
            CertInfo certInfoPri = certInfoMapper.selectCertInfoByPrimaryKey(secPlanInfoOptSign.get().getSecPlanId() + secPlanInfoOptSign.get().getSecPlanType());
            if (certInfoPri != null) {
                priKey = certInfoPri.getCertValue();
            }
        }
        /* 获取签名验签证书 */
        Optional<SecPlanInfo> secPlanInfoOpt = secPlanInfoList.stream().filter(item -> item.getSecPlanType().equals(AlipayParamConstant.VERIFY_CERT_TYPE)).findFirst();
        if (secPlanInfoOpt.isPresent()) {
            CertInfo certInfoPub = certInfoMapper.selectCertInfoByPrimaryKey(secPlanInfoOpt.get().getSecPlanId() + secPlanInfoOpt.get().getSecPlanType());
            if (certInfoPub != null) {
                pubKey = certInfoPub.getCertValue();
            }
        }
        rglog.debug("aliPayUrl = <{}>;appId = <{}>;priKey = <{}>;msgType = <{}>,charset = <{}>,pubKey = <{}>,signType = <{}>,proxyIp = <{}>,proxyPort = <{}>",
                aliPayUrl, dstChannelCfg.getAppId(), priKey, msgType, charset, pubKey, signType, proxyIp, proxyPort);
        AlipayClient alipayClient = new DefaultAlipayClient(aliPayUrl, dstChannelCfg.getAppId(),
                priKey, msgType, charset, pubKey, signType, proxyIp, proxyPort);
        AntMerchantExpandIndirectActivityConfirmRequest confirmRequest = new AntMerchantExpandIndirectActivityConfirmRequest();
        AntMerchantExpandIndirectActivityConfirmModel model = new AntMerchantExpandIndirectActivityConfirmModel();
        model.setOrderId(activityConfirmRequest.getActivityId());
        confirmRequest.setBizModel(model);
        AntMerchantExpandIndirectActivityConfirmResponse response = alipayClient.execute(confirmRequest);
        if (response.isSuccess()) {
            activityConfirmResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
            activityConfirmResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        } else {
            activityConfirmResponse.setRespCode((null == response.getSubCode()) ? response.getCode() : response.getSubCode());
            activityConfirmResponse.setRespDesc((null == response.getSubMsg()) ? response.getMsg() : response.getSubMsg());
        }
        chnlBizResponse.setResult(activityConfirmResponse);
        return chnlBizResponse;
    }

    @Override
    protected void afterBizProcess(ChnlBizResponse response) throws Exception {
        ActivityConfirmResponse activityConfirmResponse = (ActivityConfirmResponse) response.getResult();
        ConvertUtil.convertInput(activityConfirmResponse);
    }
}
